package com.hiray.demos.widget

import android.content.Context
import android.graphics.*
import android.os.Build
import androidx.core.content.ContextCompat
import android.text.TextPaint
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import com.hiray.demos.R

/**
 * Created by hiray on 2018/5/24.
 *@author hiray
 */
class SurfaceViewPanel : SurfaceView, Runnable, SurfaceHolder.Callback {
    val TAG = "SurfaceViewPanel"
    var mHolder: SurfaceHolder
    var isRunning: Boolean = false
    var mThread: Thread? = null
    lateinit var mCanvas: Canvas
    var bgBitmap: Bitmap
    var mRadius: Int = 0
    var mStartAngle = 0f
    var mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    var mTextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
    lateinit var mRectF: RectF
    val mTexts = arrayListOf("iPad", "Mac", "iPhone", "OPPO", "胡萝卜", "谢谢参与")
    val mImages = arrayListOf(R.mipmap.ipad, R.mipmap.mac, R.mipmap.iphone, R.mipmap.oppo, R.mipmap.carrot, R.mipmap.thanks)
    var icons: Array<Bitmap>
    lateinit var pointer: Bitmap
    var currAngle: Float = 0f
    val MAX_VELOCITY: Float = 600f
    var step:Float=0f
    var accelerating: Boolean = true
    val mColors = arrayListOf(Color.GREEN, Color.CYAN, Color.BLUE,
            Color.YELLOW, Color.WHITE, Color.MAGENTA)

    override fun run() {

        val opt = BitmapFactory.Options()
        opt.outHeight = (mRectF.height() * 0.2).toInt()
        pointer = BitmapFactory.decodeResource(resources, R.mipmap.pointer, opt)


        while (isRunning) {
            val startTime = System.currentTimeMillis()
            calcSpeed()
            drawPanel()
            val endTime = System.currentTimeMillis()
            if (endTime - startTime < 100) {
                Thread.sleep(100 - endTime + startTime)
            }
        }
    }

    private fun calcSpeed() {
        if (accelerating) {
            step+=20f
            if (step >= MAX_VELOCITY)
                accelerating = false
        } else {
            step-=10f
        }
    }

    private fun drawPanel() {

        try {
            mCanvas = mHolder.lockCanvas()
            mCanvas.drawColor(ContextCompat.getColor(context, R.color.colorPrimary))
            var angle = mStartAngle + currAngle
            var sweepAngle = 360f / mTexts.size
            for (i in mColors.indices) {
                mPaint.color = mColors[i]
                mCanvas.drawArc(mRectF, angle, sweepAngle, true, mPaint)
                angle += sweepAngle
            }

            angle = mStartAngle + currAngle
            for (j in mTexts.indices) {
                drawText(mTexts[j], angle, sweepAngle)
                angle += sweepAngle
            }

            angle = mStartAngle + currAngle
            for (k in icons.indices) {
                drawIcon(icons[k], angle, sweepAngle)
                angle += sweepAngle
            }
            drawArrowPointer()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (mCanvas != null)
                mHolder.unlockCanvasAndPost(mCanvas)
        }


    }

    private fun drawArrowPointer() {
        val left = mRectF.centerX() - pointer.width / 2
        val top = mRectF.centerY() - mRectF.height() / 2 * 0.4f
        mCanvas.drawBitmap(pointer, left, top, mPaint)
    }

    private fun drawIcon(icon: Bitmap, angle: Float, sweepAngle: Float) {
        //先把图标在0度的位置绘制出来，然后通过旋转画布的方式将其旋转到对应的扇形区域
        //绘制文字同理
        mCanvas.save()
        mCanvas.rotate(90 + angle + sweepAngle / 2, mRectF.centerX(), mRectF.centerY())
        val anchorX = mRectF.centerX()
        val anchorY = mRectF.centerY() - mRectF.height() * 0.28f
        val left = anchorX - icon.width / 2
        mCanvas.drawBitmap(icon, left, anchorY, mPaint)
        mCanvas.restore()
    }

    private fun drawText(text: String, angle: Float, sweepAngle: Float) {
        var textWidth = mTextPaint.measureText(text)
        mCanvas.save()
        mCanvas.rotate(90 + angle + sweepAngle / 2, mRectF.centerX(), mRectF.centerY())
        mCanvas.drawText(text, 0, text.length, mRectF.centerX() - textWidth / 2, -mRectF.height() * 0.35f + mRectF.centerY(), mTextPaint)
        mCanvas.restore()
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mRectF = RectF(0f, 0f, measuredWidth.toFloat(), measuredHeight.toFloat())
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
        Log.i(TAG, ":surfaceChanged ")
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        Log.i(TAG, ":surfaceDestroyed ")
        isRunning = false
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        Log.i(TAG, ":surfaceCreated ")
        mPaint.style = Paint.Style.FILL
        mTextPaint.style = Paint.Style.FILL_AND_STROKE
        mTextPaint.textAlign = Paint.Align.LEFT
        mTextPaint.color = Color.RED
        mTextPaint.textSize = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 22f, resources.displayMetrics);
        isRunning = true
        mThread = Thread(this)
        mThread?.start()
    }

    fun startLuckyRoll() {
        accelerating= true
        mThread = Thread(this)
        mThread?.start()
    }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        mHolder = holder
        mHolder.addCallback(this)
        keepScreenOn = true
        if (Build.VERSION.SDK_INT >= 26)
            focusable = View.FOCUSABLE
        isFocusableInTouchMode = true
        bgBitmap = BitmapFactory.decodeResource(resources, R.mipmap.square)
        icons = Array<Bitmap>(mImages.size, { i -> BitmapFactory.decodeResource(resources, mImages[i]) })
    }
}